<template>
  <div class="viewContain">
    <div style="text-align:right">
      <el-button v-if="isAdminRole === '1'" :disabled="refundDetail.status === '已退款'" type="primary" size="mini" @click="handleEdit()">修改退货单</el-button>
      <el-button v-if="isAdminRole === '1'" :disabled="refundDetail.status === '已退款'" type="primary" size="mini" @click="handleRefundConfirm()">退款</el-button>
      <el-button type="primary" size="mini" @click="handleBack()">返回</el-button>
    </div>
    <el-form size="small" label-width="100px">
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="总金额(元):">
            {{ totalPrice || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="退货单号:">
            {{ refundDetail.returnNum || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item v-if="refundDetail.type !== '其他方式'" label="发货人:">
            {{ refundDetail.shipper || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="订单状态:">
            {{ refundDetail.status || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="站点信息:">
            {{ refundDetail.orgName || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item v-if="refundDetail.type !== '其他方式'" label="物流公司:">
            {{ refundDetail.logisticsCompany || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="退货时间:">
            {{ refundDetail.createTime || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="退货方式:">
            {{ refundDetail.type || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item v-if="refundDetail.type !== '其他方式'" label="快递单号:">
            {{ refundDetail.trackNum || '暂无数据' }}
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item v-if="refundDetail.type === '其他方式'" label="备注:">
            {{ refundDetail.remark || '暂无数据' }}
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      ref="table"
      v-loading="loading"
      fit
      stripe
      :data="tableData"
      border
      size="mini"
    >
      <el-table-column align="center" label="序号" type="index" width="50">
        <template slot-scope="scope">
          <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="photo" align="center" label="商品图片">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.photo"
            style="width: 40px; height: 40px"
            :src="scope.row.photo"
          />
          <img v-else width="40px" height="40px" src="@/assets/images/noneImg.jpg">
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="商品名称" />
      <el-table-column prop="code" align="center" label="商品编号" />
      <el-table-column prop="totalPrice" align="center" label="商品总额(元)" />
      <el-table-column prop="stock" align="center" label="商品数量" />
    </el-table>
    <pagination
      :total-count="totalCount"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <!-- 退款对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="1000px"
      @close="closeDialog"
    >
      <div class="refundInfo">
        <div>当前站点 : {{ currentOrgName }}</div>
        <div><el-button size="mini" type="primary" @click="handleAddRefundItem">新增</el-button></div>
      </div>
      <el-form ref="formData" :model="formData" size="small" :rules="rules" label-width="100px">
        <div class="refundTable">
          <el-table
            ref="table"
            v-loading="loading"
            fit
            stripe
            :data="tableDataRefund"
            border
            size="mini"
            style="margin-bottom:20px"
          >
            <el-table-column align="center" label="序号" type="index" width="50">
              <template slot-scope="scope">
                <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" align="center" label="商品信息">
              <template slot-scope="scope">
                <el-select v-model="scope.row.code" placeholder="请选择" clearable style="width:100%">
                  <el-option
                    v-for="item in goodList"
                    :key="item.value"
                    :label="item.label + '(' + item.code + ')'"
                    :value="item.code"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="stock" align="center" label="商品数量" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" />
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="50">
              <template slot-scope="scope">
                <el-button class="text-button el-button--danger" size="mini" @click="handleDeleteRefundItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="物流退货" name="物流">
            <el-form-item label="物流公司 :" prop="logisticsCompany">
              <el-select
                v-model="logisticsCompany"
                placeholder="请选择"
                clearable
                style="width:100%"
                @change="select"
              >
                <el-option
                  v-for="item in logisticsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="物流单号 :" prop="trackNum">
              <el-input v-model="formData.trackNum" clearable style="width:100%" />
            </el-form-item>
            <el-form-item label="发货人 :" prop="shipper">
              <el-input v-model="formData.shipper" style="width:100%" clearable />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="其它" name="其它方式">
            <el-form-item label="备注 :" prop="remark">
              <el-input v-model="formData.remark" clearable type="textarea" :rows="2" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        <el-form-item>
          <div style="text-align:right">
            <el-button size="mini" type="primary" plain @click="handleClose">取消</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit">提交</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { commonMixin } from '@v/mixin/commonMixin.js'
import ComApiUrl from '@a/comomApi.js'
import { queryReturnRecordDetail, returnHandler } from '@a/business/site.js'
import { queryProductList } from '@a/business/site.js'
import { mapGetters } from 'vuex'
import pagination from '@/components/pagination/index.vue'

export default {
  components: { pagination },
  mixins: [commonMixin],
  data() {
    return {
      comApiUrlUpdate: new ComApiUrl('/member/api/returnGoods/updateReturnRecord'),
      loading: false,
      routePath: '',
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        returnNum: ''
      },
      refundDetail: {},
      tableData: [], // 分页展示的退款单
      tableDataAll: [], // 总的退款单
      dialogTitle: '退货单',
      dialogFormVisible: false,
      tableDataRefund: [],
      goodList: [],
      activeName: '物流',
      currentOrgName: '', // 站点名称
      formData: {
        returnGoodsBeans: [], // 商品集合
        logisticsCompany: '',
        trackNum: '', // 物流单号
        shipper: '', // 发货人
        type: '', // 退货方式（默认物流）
        orgId: '', //  机构id
        remark: '',
        code: ''
      },
      rules: {
        trackNum: [
          { required: true, message: '物流单号不能为空!', trigger: 'blur' }
        ],
        shipper: [
          { required: true, message: '发货人不能为空!', trigger: 'blur' }
        ],
        logisticsCompany: [
          { required: true, message: '物流公司不能为空!', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '备注不能为空!', trigger: 'blur' }
        ]
      },
      isAdminRole: '',
      rule: true,
      type: '',
      totalCount: 0, // 分页参数
      logisticsCompany: '', // 默认选中的物流公司
      totalPrice: '' // 总金额
    }
  },
  computed: {
    ...mapGetters(['logisticsList'])
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const { isAdminRole, orgId, orgName } = userInfo
    this.formData.orgId = userInfo.orgId
    isAdminRole === '1' ? this.formData.orgId = localStorage.getItem('orgId') : this.formData.orgId = orgId
    this.isAdminRole = userInfo.isAdminRole
    isAdminRole === '1' ? this.currentOrgName = localStorage.getItem('orgName') : this.currentOrgName = orgName
    this.listQuery.returnNum = this.$route.params.id
    this.totalPrice = localStorage.getItem('totalPrice')
    this.routePath = this.$route.params.id
    this.getList()
    this.getTableDataAll()
  },
  methods: {
    getList() {
      // 退款table列表
      queryReturnRecordDetail(this.listQuery).then(res => {
        // console.log(res)
        this.refundDetail = res.data.list[0]
        this.activeName = res.data.list[0].type
        this.activeName === '物流' ? this.formData.type = '0' : this.formData.type = '1'
        this.tableData = res.data.list
        this.totalCount = res.data.total
      })
    },
    // 退款弹窗table列表
    getTableDataAll() {
      const returnNum = this.$route.params.id
      queryReturnRecordDetail({ returnNum, pageSize: 999999 }).then(res => {
        // console.log(res)
        this.tableDataAll = res.data.list
        this.tableDataAll.forEach(item => {
          this.tableDataRefund.push({
            code: item.code, label: item.name, stock: item.stock, type: item.type, remark: item.remark
          })
        })
        // console.log(this.tableDataRefund)
      })
    },
    // 新增退款条例
    handleAddRefundItem() {
      this.tableDataRefund.push({})
    },
    // 修改
    handleEdit() {
      this.dialogFormVisible = true
      console.log(this.listQuery)
      this.listQuery.pageNo = 1 // 确保分页参数不影响table表格序号排序
      // 商品列表下拉框
      // console.log(this.tableDataRefund)
      this.tableDataRefund[0].type === '物流' ? this.activeName = '物流' : this.activeName = '其它方式'
      this.formData.remark = this.tableDataRefund[0].remark
      // 商品列表去重
      var result = []
      var obj = {}
      for (var i = 0; i < this.tableDataRefund.length; i++) {
        if (!obj[this.tableDataRefund[i].code]) {
          result.push(this.tableDataRefund[i])
          obj[this.tableDataRefund[i].code] = true
        }
      }
      this.tableDataRefund = result
      // console.log(this.tableDataRefund)
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      const { userId, isAdminRole } = userInfo
      const id = this.$route.params.id
      let orgId = ''
      isAdminRole === '1' ? orgId = localStorage.getItem('orgId') : orgId = userInfo.orgId
      // 可以操作退货的商品列表
      queryProductList({ id: userId, orgId }).then(res => {
        if (res.code === 0) {
          this.goodList = res.data
          queryReturnRecordDetail({ returnNum: id }).then(res1 => {
            console.log(res1)
            this.formData.trackNum = res1.data.list[0].trackNum
            this.formData.shipper = res1.data.list[0].shipper
            this.formData.returnNum = res1.data.list[0].returnNum
            this.logisticsCompany = res1.data.list[0].logisticsCompany
            this.formData.logisticsCompany = res1.data.list[0].logisticsCompanyCode
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    select(val) {
      // console.log(val)
      this.formData.logisticsCompany = String(val)
    },
    // 修改后提交退货单
    handleSubmit() {
      // console.log(this.tableDataRefund)
      if (this.tableDataRefund.length) {
        delete this.tableDataRefund[0].label
        this.formData.returnGoodsBeans = this.tableDataRefund
        for (var i = 0; i < this.formData.returnGoodsBeans.length; i++) {
          if (!this.formData.returnGoodsBeans[i].stock) {
            this.$message({
              type: 'warning',
              message: '商品采购数量不能为空!'
            })
            this.rule = false
            break
          } else {
            const reg = new RegExp(/^[0-9]*[1-9][0-9]*$/) // 商品数量要是大于0的正整数
            const flag = reg.test(this.formData.returnGoodsBeans[i].stock)
            if (!flag) {
              this.$message({
                type: 'warning',
                message: '商品数量为大于0的正整数!'
              })
              this.rule = false
              break
            } else {
              this.rule = true
            }
          }
          if (!this.formData.returnGoodsBeans[i].code) {
            this.$message({
              type: 'warning',
              message: '请选择商品!'
            })
            this.rule = false
            break
          } else {
            this.rule = true
          }
        }
        // 判断重复的商品
        const code = this.formData.returnGoodsBeans.map(item => item.code)
        // console.log(code)
        const codeSet = new Set(code)
        if (codeSet.size === code.length) {
          // console.log('不存在同个值')
        } else {
          this.$message({
            type: 'warning',
            message: '该商品已经在退货单中!'
          })
          this.rule = false
        }
        if (this.formData.type === '0') { // 提交物流方式退货表单
          delete this.rules.remark
          this.$refs.formData.validate(valide => {
            if (valide && this.rule) {
              this.update()
            }
          })
        } else { // 提交其它方式退货表单
          delete this.rules.trackNum
          delete this.rules.shipper
          delete this.rules.logisticsCompany
          this.$refs.formData.validate(valide => {
            if (valide && this.rule) {
              this.update()
            }
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '不能提交空白退款单!'
        })
      }
    },
    // 删除退款条例
    handleDeleteRefundItem(index) {
      // console.log(index)
      this.tableDataRefund.splice(index, 1)
    },
    // 确认退款
    handleRefundConfirm() {
      this.$confirm('是否确认该单已退款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: ''
      }).then(() => {
        const returnParams = {
          returnGoodsBeans: this.tableDataRefund,
          returnNum: this.routePath
        }
        // console.log(returnParams)
        returnHandler(returnParams).then(res => {
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '退款成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
          this.getList()
        })
      })
    },
    // 取消退款
    handleClose() {
      this.dialogFormVisible = false
      this.$refs.formData.resetFields()
    },
    handleClick(tab) {
      // console.log(tab)
      this.formData.type = tab.index
    }
  }
}
</script>
<style lang="scss" scoped>
.refundInfo {
  width: 100%;
  height: 50px;
  line-height: 50px;
  display: flex;
  justify-content:space-between;
}
.refundTable {
  width: 100%;
  height: 250px;
  overflow: auto;
}
</style>
